/*
Javascript iFrame AdBlocker Detector for jQuery

Version: 0.1
Author: David Rietz (TMKILLA) - http://www.tmkilla.com - http://twitter.com/tmkilla
Source code repository: https://jqiabd.codeplex.com/

This code is licensed under the Creative Commons Attribution 3.0 Unported License 
(http://creativecommons.org/licenses/by/3.0/).
*/
(function ($) {

    var settings = {
        'frameId'         : '',
        'fallbackUrl'     : '',
        'forwardTimeout'  : 100,
        'beforeForward'   : function () {},
        'start'           : 0,
        'end'             : 0,
        'loggingEnabled'  : false,
        'log'             : '',
        'logdisplay'      : null
    };
    
    var methods = {
        
        init: function (options) {
            $.extend(settings, options);
            
            settings.start = new Date().getTime();
            methods.log.call(this, 'Start: ' + settings.start);
            
            $(window).bind('load.iframeadblockdetector', methods.loadCompleted);
            
            return this;
        },
        
        loadCompleted: function () {
            settings.end = new Date().getTime();
            methods.log.call(this, 'Method called: loadCompleted');
            methods.log.call(this, 'End: ' + settings.end);
            methods.log.call(this, 'Loading time (ms): ' + (settings.end - settings.start));
            
            setTimeout(function () {
                $(this).iframeAdblockDetector('detectSuccessfullDisplay');
            }, 100);
            
            return this;
        },
        
        detectSuccessfullDisplay: function () {
            var frame = document.getElementById(settings.frameId);
            var isChrome = /chrome/.test(navigator.userAgent.toLowerCase());
            
            methods.log.call(this, 'Google Chrome: ' + isChrome);
            methods.log.call(this, 'Frame (DOM): ' + frame);
            
            if (frame == null || frame == 'undefined') {
                return methods.forward.call(this);
            }
            
            try { 
                var jqFrame = $('#' + settings.frameId);
                methods.log.call(this, 'Frame (jQuery): ' + jqFrame);
                methods.log.call(this, 'Frame Contents (jQuery): ' + jqFrame.contents());
                methods.log.call(this, 'Frame Contents Count (jQuery): ' + jqFrame.contents().length);
                
                if (jqFrame.contents().length == 1) 
                    methods.log.call(this, 'Frame Contents [0] (jQuery): ' + jqFrame.contents()[0]);
                    
                methods.log.call(this, 'Frame Contents HTML (jQuery): ' + jqFrame.contents().html());
                
                if (isChrome) {
                    if (jqFrame == undefined) {
                        return methods.forward.call(this);
                    }
                    else if (jqFrame.contents() != undefined && jqFrame.contents().length == 1) {
                        return methods.forward.call(this);
                    }
                }
                else {
                    if (jqFrame == undefined || jqFrame.contents() == undefined || jqFrame.contents().length != 1 || jqFrame.contents().html() == undefined) {
                        return methods.forward.call(this);
                    }
                }
            }
            catch (ex) {
                methods.log.call(this, 'Frame (jQuery) access raised an exception, normally a signal for successful load of the frame\'s content (3rd party content): ' + ex);
            }
        
            return this;
        },
        
        forward: function () {
            methods.log.call(this, 'Method called: forward');
            methods.log.call(this, 'Frame seems to be loaded invalidly. Forwarding to your desired fallback page in ' + settings.forwardTimeout + 'ms...');

            if (settings.fallbackUrl == '') 
                methods.log.call(this, 'Forwarding impossible due to invalid fallback URL.');
                
            settings.beforeForward.call(this);
            
            setTimeout(function () {
              location.href = settings.fallbackUrl;
            }, settings.forwardTimeout);
            
            return this;
        },
        
        log: function (message) {
            if (!settings.loggingEnabled) return this;
        
            settings.log += "[" + new Date().toString() + "] " + message + "\r\n";
            
            if (settings.logdisplay != null) {
                settings.logdisplay.val(settings.log);
            }
            
            return this;
        }
        
    };
    
    $.fn.iframeAdblockDetector = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.iframeAdblockDetector!');
        }
    }

})(jQuery);